package com.pdg.android.common;

import java.util.HashMap;
import java.util.Map;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;

public abstract class StateMachine<S extends GameDataBase<U>,T extends StateMachine<S,T,U>,U> extends Activity {
	private S data;
	private Map<U,State<S,T,U>> states = new HashMap<U,State<S,T,U>>();
	private U current;
	
	protected void putState(State<S,T,U> theValue){
		states.put(theValue.getId(),theValue);
	}
	protected State<S,T,U> getState(U theKey){
		return states.get(theKey);
	}
	public void setCurrent(U theCurrent){
		State<S,T,U> theState = getState(getCurrent());
		if(theState!=null){
			theState.leave();
		}
		current = theCurrent;
		onSetCurrent(theCurrent);
		theState = getState(getCurrent());
		if(theState!=null){
			theState.enter();
		}
	}
	protected abstract void onSetCurrent(U theCurrent);
	public U getCurrent(){
		return current;
	}
	
	public StateMachine(S theData,U theCurrent){
		setData(theData);
		getData().setContext(this);
		current = theCurrent;
	}
	private void setData(S theData) {
		data = theData;
	}
	protected S getData(){
		return data;
	}
	@Override
	protected void onCreate(Bundle savedInstanceState){
    	super.onCreate(savedInstanceState);
    	setCurrent(getCurrent());
    }

	@Override
    protected void onStart(){
    	super.onStart();
    }
    
	@Override
    protected void onRestart(){
    	super.onRestart();
    }

	@Override
    protected void onResume(){
    	super.onResume();
    }

	@Override
    protected void onPause(){
    	super.onPause();
    }

	@Override
    protected void onStop(){
    	super.onStop();
    }

	@Override
    protected void onDestroy(){
    	super.onDestroy();
    }
    public void buttonPressed(View theView){
    	getState(getCurrent()).buttonPressed(theView.getId());
    }
}
